Writing XML with the XmlDocument class in C#

In the previous section, we used the XML XmlWriter class. However, for some situations, especially when using XmlDocument classes can be done while updating existing XML, you should be aware of high memory consumption, mainly for large XML documents here are some code:


using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode rootNode = xmlDoc.CreateElement("users");
            xmlDoc.AppendChild(rootNode);

            XmlNode userNode = xmlDoc.CreateElement("user");
            XmlAttribute attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "42";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "John Doe";
            rootNode.AppendChild(userNode);

            userNode = xmlDoc.CreateElement("user");
            attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "39";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Jane Doe";
            rootNode.AppendChild(userNode);

            xmlDoc.Save("test-doc.xml");
        }
    }
}

And the resulting XML:


<users>
  <user age="42">John Doe</user>
  <user age="39">Jane Doe</user>
</users>
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("test-doc.xml");
            XmlNodeList userNodes = xmlDoc.SelectNodes("//users/user");
            foreach(XmlNode userNode in userNodes)
            {
                int age = int.Parse(userNode.Attributes["age"].Value);
                userNode.Attributes["age"].Value = (age + 1).ToString();
            }
            xmlDoc.Save("test-doc.xml");           
        }
    }
}

We load the XML file and ask for all the <user> nodes. We then iterate through them, read the age attribute into an integer variable, and then we write the value back to the node and attribute, after increasing the value by 1. At last, we save the document back to the same file and if you open it up, you will see that our users all just had a birthday. Pretty good!

As you can see, this is slightly more object-oriented than the XmlWriter approach, and requires a bit more code for it. What we do is that we instantiate an XmlDocument object, which we will use to create both new elements and attributes using CreateElement () and CreateAttribute () methods. Whenever we do this, we add elements, either directly into the document or any other element You can see it in this example, where the original element ("user") is directly added to the document, while the user element is connected to the original element. Using the append () method on the attribute property, those elements are added, where they are related. The entire XML document is written to disk on the last line, where we use the Save () method.

Now, as mentioned earlier, using a XMLRector requires a bit more code, but imagine a situation where you should go to the existing XML document and change some values. Using the XmlWriter approach, you have to save it to use XmlReader first, change it, and then write back the entire information using XmlWriter because XmlDocument keeps everything in your memory, because the existing XML file update It is very easy to do. The following example opens the "test-doc.xml" file that we created in the previous chapter and each user's age increases according to one. See how easy it is: